<template>
  <div class="">
    <el-form ref="form" :model="form" class="formEmbedTableRefactor mb20">
      <table>
        <caption>A/C Information</caption>
        <tr>
          <td><div style="min-width:108px;text-align:center"><span class="cRed">*</span>Primary A/C No.</div></td> 
          <td>
            <el-form-item 
              prop="acctNo"
              :rules="{trigger:'blur',validator:this.validateAcctNo,required: true}">
              <el-input v-model="form.acctNo"></el-input>
            </el-form-item>
          </td>
          <td><div style="min-width:64px;text-align:center"><span class="cRed">*</span>A/C Type</div></td> 
          <td>
            <el-form-item 
              prop="acctType"
              :rules="{trigger:'change',validator:this.validateAcctType,required: true}">
            <!--<el-form-item>-->
              <!--<div v-model="form.acctType" style="min-width:60px">港币存储</div>-->
              <!--<el-select v-model="form.primaryAcct.acctType" @change="validateAcctType">-->
                <el-select v-model="form.acctType">
                  <el-option label="Savings" value="P"></el-option>
                  <el-option label="Time deposit" value="S"></el-option>
              </el-select>
            </el-form-item>
          </td>
          <td>Transfer Cycle Limit</td> 
          <td>
            <el-form-item>
              <span>{{form.tranCycleLimit}}</span>
            </el-form-item>
          </td>
          <td>HKD Bill Payment Cycle Limit</td> 
          <td>
            <el-form-item>
              <span>{{form.bpCycleLimit}}</span>
            </el-form-item>
          </td>
          <td>Fixed Deposit Cycle Limit</td> 
          <td>
            <el-form-item>
              <span>{{form.fixedDepCycleLimit}}</span>
            </el-form-item>
          </td>
          <td v-if="form.relatedAcctList.length > 0"></td>
        </tr>

        <tr v-for="(item,index) in form.relatedAcctList">
          <td><div style="min-width:108px;text-align:center">A/C No.</div></td>
          <td>
            <el-form-item 
              :prop="'relatedAcctList.'+ index + '.acctNo'" 
              :rules="relatedAcctRule(index,item.subType)"
            >
              <!--<el-input v-model="form.relatedAcctList[index].relatedAcct"></el-input>-->
              <el-input v-model="item.acctNo"></el-input>
            </el-form-item>
          </td>
          <td><div style="min-width:64px;text-align:center">A/C Type</div></td> 
          <td>
            <el-form-item 
              :prop="'relatedAcctList.'+ index + '.subType'"
              :rules="relatedAcctTypeRule(index)"
            >
              <!--<div v-model="form.relatedAcctList[index].acctType" style="min-width:60px"></div>-->
              <el-select v-model="item.subType">
                  <el-option label="Savings" value="P"></el-option>
                  <el-option label="Time deposit" value="S"></el-option>
              </el-select>
            </el-form-item>
          </td>
          <td>Transfer Cycle Limit</td> 
          <td>
            <el-form-item>
              <span>{{form.tranCycleLimit}}</span>
            </el-form-item>
          </td>
          <td>HKD Bill Payment Cycle Limit</td> 
          <td>
            <el-form-item>
              <span>{{form.bpCycleLimit}}</span>
            </el-form-item>
          </td>
          <td>Fixed Deposit Cycle Limit</td> 
          <td>
            <el-form-item>
              <span>{{form.fixedDepCycleLimit}}</span>
            </el-form-item>
          </td>
          <td><el-button @click="deleteRelatedAcct(index)">Delete</el-button></td>
        </tr>
      </table>
      <div class="btnArea tac">
        <el-button type="primary" @click="addRelatedAcct">Add</el-button>
      </div>
    </el-form>

    <el-form class="formEmbedTable mb20">
      <table>
        <caption>CUS Information</caption>
        <tr>
          <td>CUS.ID</td>
          <td>
            <span class="cOrange">{{form.cusID}}</span>
          </td>
        </tr>   
        <tr v-for="legal in form.cstInfo.legalList">
          <td>CNTY</td>
          <td>
            <span class="cOrange">{{legal.cntyCode}}</span>
          </td>
          <td>Document Type</td>
          <td>
            <span class="cOrange">{{legal.docType}}</span>
          </td>
          <td>Document Number</td>
          <td>
            <span class="cOrange">{{legal.docNo}}</span>
          </td>
        </tr>
      </table>
    </el-form>

    <el-form ref="form2" :model="form" :rules="rules" class="formEmbedTable mb20">
      <table>
        <!--<caption>证件信息</caption>-->
        <tr>
          <td>A/C Address</td>
          <td>
            <span class="cOrange">{{form.acc_addr1}} {{form.acc_addr2}} {{form.acc_addr3}} {{form.acc_addr4}}</span>
          </td>
        </tr>   
        <tr>
          <td>ADDR.COUNTRY</td>
          <td>
            <span class="cOrange">{{form.addr_cntry_code}}</span>
          </td>
        </tr>
        <tr>
          <td><span class="cRed">*</span>Authorized Person</td>
          <td>
            <el-form-item prop="authorPerson">
              <el-input v-model="form.authorPerson"></el-input>
            </el-form-item>
          </td>
        </tr>
      </table>
    </el-form>

    <div class="btnArea mt20 tac">
        <el-button type="primary" @click="nextStep">Next</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name:'fillinPage',
  components: {
  },
  props: {
    fillinMsg:{
      type: Object
    }
  },
  data() {
    return {
      acc_not_exist_flag: 'N',//not exist indicator
      acc_inactiv_flag: 'Y',//inactive indicator
      acc_restric_flag: 'Y',//restrict indicator
      acctList:[],
      form:{
        acctNo: '',
        acctType: '',
        // primaryAcct:{
        //   acctNo: '',
        //   acctType: ''
        // },
        cusID: '',
        relatedAcctList: [],
        tranCycleLimit: '',
        bpCycleLimit: '',
        fixedDepCycleLimit: '',
        acc_addr1: '',
        acc_addr2: '',
        acc_addr3: '',
        acc_addr4: '',
        addr_code: '',
        addr_cntry_code: '',
        authorPerson: '',
        currency: '',
        category: '',
        cstInfo:{
          legalList: [],
          cusNameEn: '',
          cusNameCn: '',
          mobCntyCode: '',
          mobArea: '',
          mobPhoneNo: '',
          cusSegment: '',
          sector: ''
        }
      },
      rules:{
        acctNo:[
          {trigger:'blur',validator:this.validateAcctNo,required: true}
        ],
        // relatedAcctNo:[
        //   {trigger:'blur',validator:this.validateRelatedAcctNo,required: true}
        // ],
        acctType:[
          {trigger:'change',validator:this.validateAcctType,required: true}
        ],
        authorPerson: [
          {trigger:'blur',validator:this.validateAuthorPerson,required: true}
        ]
      },
      skipValidate: false
    }
  },
  mounted(){
    let _this = this
    _this.form  = $.extend({},_this.form,_this.fillinMsg)   //从父组件传来的值可能是空或对象
    _this.$tools.request(_this,"IM040103.do",{}).then(
      data=>{
        let errorCode = data.body.errorCode
        let errorMsg = "System Error Try again";
        if(errorCode =='0'){
          let limitType = data.body.limitType
          if(limitType){
            let limitList = []
            if(limitType == 'A'){//账户限额
              limitList = data.body.acctLimit || []
              for(let i = 0; i < limitList.length; i++){
                let obj = limitList[i]
                if(obj.TBL_LIMITTYPE == 'P')  _this.form.bpCycleLimit = obj.TAL_DAY_LIMIT
                if(obj.TBL_LIMITTYPE == 'T')  _this.form.tranCycleLimit = obj.TAL_DAY_LIMIT
                if(obj.TBL_LIMITTYPE == 'F')  _this.form.fixedDepCycleLimit = obj.TAL_DAY_LIMIT
              }
            }
            if(limitType == 'B'){//银行限额
              limitList = data.body.bankLimit || []
              for(let i = 0; i < limitList.length; i++){
                let obj = limitList[i]
                if(obj.TBL_LIMITTYPE == 'P')  _this.form.bpCycleLimit = obj.TBL_DAY_LIMIT
                if(obj.TBL_LIMITTYPE == 'T')  _this.form.tranCycleLimit = obj.TBL_DAY_LIMIT
                if(obj.TBL_LIMITTYPE == 'F')  _this.form.fixedDepCycleLimit = obj.TBL_DAY_LIMIT
              }
            }
          }
        }else{
          _this.$alert(errorMsg, 'Error', {confirmButtonText: 'OK'});
        }
      }
    )
  },
  methods: {
    deleteRelatedAcct(index){
      console.log("delete acct index:", index)
      let _this = this
      if(index >= 0){
        _this.form.relatedAcctList.splice(index, 1)
      }
    },
    addRelatedAcct(){
      let _this = this
      let acct = {}
      // acct.relatedAcct = ''
      acct.acctNo = ''
      acct.subType = ''
      // acct.acctType = ''
      _this.form.relatedAcctList.push(acct)
    },
    isEmpty(rule, value, callback){
      if ($.trim(value) == "") callback('内容不能为空')
      callback()
    },
    resetForm(formName) {//重置事件
      let _this = this
      _this.$refs[formName].resetFields()
      _this.form.balanceIndex=1
    },
    validateAcctNo(rule, value, callback){
      // debugger
      let _this = this
      if(!value.trim()){
        callback("A/C No. is required")
        return
      }
      if(!(/^[0-9a-zA-Z]*$/g.test(value))){
        callback("invalid A/C No.")
        return
      }
      if(!_this.form.acctType){
        callback("Please select A/C Type")
        return
      }
      if(!_this.skipValidate){
        _this.queryAcctInfo(callback)
      }else{
        callback()
      }
    },
    relatedAcctTypeRule(index){
      return [{trigger:'blur',validator:this.validateRelatedAcctType,index:index,required: true}]
    },
    relatedAcctRule(index,acctType){
      return [{trigger:'blur',validator:this.validateRelatedAcctNo,index:index,acctType:acctType,required: true}]
    },
    validateRelatedAcctNo(rule, value, callback){
      // debugger
      let _this = this
      let acctType = rule.acctType
      if(!value.trim()){
        callback("A/C No. is required")
        return
      }
      if(!(/^[0-9a-zA-Z]*$/g.test(value))){
        callback("invalid A/C No.")
        return
      }
      if(!acctType){
        callback("Please select A/C Type")
        return
      }
      // if(_this.acctList && _this.acctList.length <= 0)

      if(!_this.skipValidate){
        _this.queryRelatedAcctInfo(rule.index,value,acctType,callback)
      }else{
        callback()
      }
    },
    validateRelatedAcctType(rule, value, callback){
      let _this = this
      if(!value.trim()){
        callback("A/C Type is required")
        return
      }
      callback()
    },
    validateAcctType(rule, value, callback){
      // debugger
      let _this = this
      if(!value.trim()){
        callback("A/C Type is required")
        return
      }
      callback()
    },
    validateAuthorPerson(rule, value, callback){
      // debugger
      let _this = this
      if(!value.trim()){
        callback("Author Person is required")
        return
      }
      if(!(/^[\u4E00-\u9FA5A-Za-z]+$/.test(value))){//only EN/CN name is allowed
        callback("invalid name")
        return
      }
      callback()
    },
    queryCstInfo(cusID){
      let _this = this
      let body = {}
      body.cus_id = cusID
      _this.$tools.request(_this,"IM040105.do",body).then(
        data=>{
          let errorCode = data.body.errorCode
          let errorMsg = "System Error Try again";
          if(errorCode == '0'){
            _this.form.cstInfo.legalList = data.body.legalList
            _this.form.cstInfo.cusNameEn = data.body.cusNameEn
            _this.form.cstInfo.cusNameCn = data.body.cusNameCn
            _this.form.cstInfo.mobCntyCode = data.body.mobCntyCode
            _this.form.cstInfo.mobArea = data.body.mobArea
            _this.form.cstInfo.mobPhoneNo = data.body.mobPhoneNo
            _this.form.cstInfo.cusSegment = data.body.cusSegment
            _this.form.cstInfo.sector = data.body.sector
          }else{
            // _this.$alert(errorMsg, 'Error', {confirmButtonText: 'OK'});
          }
        }
      )
    },
    queryAcctInfo(callback){
      let _this = this
      let body = {}
      body.acctType = _this.form.acctType
      body.ACCTIDLIST = []
      body.ACCTIDLIST.push({acc_no:_this.form.acctNo})
      _this.$tools.request(_this,"IM040104.do",body).then(
        data=>{
          let errorCode = data.body.errorCode
          let errorMsg = "System Error Try again";
          if(errorCode == '0'){
            _this.acctList = data.body.ACCOUNTLIST
            if(_this.acctList && _this.acctList.length > 0){
              let acctInfo = _this.acctList[0]

              let ind_acc_exist = _this.form.ind_acc_exist = acctInfo.ind_acc_exist
              let inactiv_marker = _this.form.inactiv_marker = acctInfo.inactiv_marker
              let post_restric = _this.form.post_restric = acctInfo.post_restric
              // if(ind_acc_exist == _this.acc_not_exist_flag || inactiv_marker == _this.acc_inactiv_flag || post_restric == _this.acc_restric_flag){
              if(ind_acc_exist == _this.acc_not_exist_flag || inactiv_marker == _this.acc_inactiv_flag || _this.$tools.dict.checkPostingRestrict(post_restric)){
                callback('Account is not available')
                return
              }

              _this.form.cusID = acctInfo.cus_id
              _this.form.acc_addr1 = acctInfo.acc_addr1
              _this.form.acc_addr2 = acctInfo.acc_addr2
              _this.form.acc_addr3 = acctInfo.acc_addr3
              _this.form.acc_addr4 = acctInfo.acc_addr4
              _this.form.addr_code = acctInfo.addr_code
              _this.form.addr_cntry_code = acctInfo.addr_cntry_code
              _this.form.currency = acctInfo.ccy_code
              _this.form.category = acctInfo.category
              _this.queryCstInfo(_this.form.cusID)
            }
          }else{
            _this.$alert(errorMsg, 'Error', {confirmButtonText: 'OK'});
          }
          callback()
        }
      )
    },
    queryRelatedAcctInfo(listIndex,acctNo,acctType, callback){
      let _this = this
      let body = {}
      body.acctType = acctType
      body.ACCTIDLIST = []
      body.ACCTIDLIST.push({acc_no:acctNo})
      _this.$tools.request(_this,"IM040104.do",body).then(
        data=>{
          let errorCode = data.body.errorCode
          let errorMsg = "System Error Try again";
          if(errorCode == '0'){
            _this.acctList = data.body.ACCOUNTLIST
            if(_this.acctList && _this.acctList.length > 0){
              let acctInfo = _this.acctList[0]

              let ind_acc_exist = acctInfo.ind_acc_exist
              let inactiv_marker = acctInfo.inactiv_marker
              let post_restric = acctInfo.post_restric
              if(ind_acc_exist == _this.acc_not_exist_flag || inactiv_marker == _this.acc_inactiv_flag || _this.$tools.dict.checkPostingRestrict(post_restric)){
                callback('Account is not available')
                return
              }
              
              let index = listIndex
              if(index >= 0){
                _this.form.relatedAcctList[index].primaryAcctNo = _this.form.acctNo || ''
                _this.form.relatedAcctList[index].currency = acctInfo.ccy_code || ''
                _this.form.relatedAcctList[index].acctType = acctInfo.category || ''
                _this.form.relatedAcctList[index].acctNameEn = acctInfo.acc_title1 || ''//取title1
                _this.form.relatedAcctList[index].acctNameCn = acctInfo.acc_cn_title1 || ''//取title1
                // _this.form.relatedAcctList[index].cusID = _this.form.cusID
              }
              
              // _this.form.cusID = acctInfo.cus_id
              // _this.form.acc_addr1 = acctInfo.acc_addr1
              // _this.form.acc_addr2 = acctInfo.acc_addr2
              // _this.form.acc_addr3 = acctInfo.acc_addr3
              // _this.form.acc_addr4 = acctInfo.acc_addr4
              // _this.form.addr_code = acctInfo.addr_code
              // _this.form.addr_cntry_code = acctInfo.addr_cntry_code
              // _this.form.currency = acctInfo.ccy_code
              // _this.form.category = acctInfo.category
            }
          }else{
            _this.$alert(errorMsg, 'Error', {confirmButtonText: 'OK'});
          }
          callback()
        }
      )
    },
    preStep(){
      let _this = this
      _this.$emit("preStep")
    },
    nextStep(){
      // debugger
      let _this = this
      _this.skipValidate = true
      let body = {}
      body.acctFlag = '0'
      body.primaryAcctNo = _this.form.acctNo
      body.relatedAcctList = _this.form.relatedAcctList
      _this.$refs.form.validate((valid) =>{
        if(valid){
          _this.$refs.form2.validate((valid) =>{
            if(valid){
              _this.$tools.request(_this,"IM040101.do",body).then(
                data=>{
                  let errorCode = data.body.errorCode
                  let errorMsg = "System Error Try again";
                  if(errorCode =='0'){
                    _this.$emit("changeStep","1", _this.form)
                  }else{
                    if(errorCode == 'UIF08006' || errorCode == 'UIF08007'){
                      errorMsg = data.body.errorMsg
                    }
                    _this.$alert(errorMsg, 'Error', {confirmButtonText: 'OK'});
                  }
                }
              )
            }else{
              console.log("form2 invalid")
            }
          })
        }else{
          console.log("form invalid")
        }
      })
    }
  }
}
</script>
<style>
  .formEmbedTableRefactor >table{width:100%;}
  .formEmbedTableRefactor caption{ background: #aca2a0; height: 38px; line-height:38px; padding-left: 20px; font-size:16px; font-weight: normal; color: #fff; text-align:left;}
  .formEmbedTableRefactor >table tr>td,.formEmbedTableRefactor th{border:1px solid #cbcbc9;height:30px; padding:0px; }
  .formEmbedTableRefactor >table tr>td:nth-child(odd),.formEmbedTableRefactor th{background:#fff7f4;text-align:right;box-sizing: border-box; padding:4px;}
  .formEmbedTableRefactor >table tr>td:nth-child(even){padding:4px;}
  .formEmbedTableRefactor .tdBgWhite td{background:#fff;}
  .formEmbedTableRefactor .textCenter td,.formEmbedTableRefactor .textCenter th,.formEmbedTableRefactor td.textCenter,.formEmbedTableRefactor th.textCenter{text-align: center;}
  .formEmbedTableRefactor tr.bgWhite td{background:#fff;}
  .formEmbedTableRefactor tr.resetPadding td,.formEmbedTableRefactor tr.resetPadding th{width:auto; padding:4px 0px}
  .formEmbedTableRefactor tr.resetPadding .w28{width:28px;}
  .formEmbedTableRefactor tr.resetPadding .w28 .el-input__inner{padding:0px; text-align:center;}
  .formEmbedTableRefactor .el-form-item{margin:0px; display: inline-block;vertical-align: middle;}
  .formEmbedTableRefactor .el-form-item__error{left:0px;}
  .formEmbedTableRefactor .el-input{width:200px; display: inline-block;}
  .formEmbedTableRefactor .el-textarea{width:600px; display: inline-block;}
  .formEmbedTableRefactor .w300 .el-input,.formEmbedTableRefactor .w300 .el-textarea{width:300px; display: inline-block;}
  .formEmbedTableRefactor .w400 .el-input,.formEmbedTableRefactor .w400 .el-textarea{width:400px; display: inline-block;}
  .formEmbedTableRefactor td.tableEvenText{background:#fff; text-align: left;}
</style>